<template>
  <section>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="centerDialog">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表信息 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="upDateVisible(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="assignRolesDialogClick(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage4"
        :page-sizes="[1, 2, 3, 4, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="centerDialogVisible"
      width="40%"
      @close="addDialogClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机号">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="upDatedialogVisible"
      width="40%"
      @close="upDatedialogClose"
    >
      <el-form
        :model="upDateForm"
        :rules="upDateFormRules"
        ref="upDateFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名:">
          <el-input v-model="upDateForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="upDateForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile">
          <el-input v-model="upDateForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="upDatedialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="upDateUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="assignRolesDialog"
      width="50%"
      :before-close="handleClose"
      @close="setRoleDialogClosed"
    >
      <span>
        <p>当前用户：{{ userInfo.username }}</p>
        <p>当前用户角色：{{ userInfo.role_name }}</p>
        <p>
          选择角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </section>
</template>
<script>
import {
  requestGet,
  requestPut,
  requestPost,
  requestDelete
} from "../../request/request";
export default {
  name: "",
  data() {
    // 自定义邮箱校验规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    // 自定义手机号校验规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(1[3|5-9])\d{9}$/;

      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };

    return {
      // 分配角色对话框显示
      assignRolesDialog: false,
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      total: 0,
      centerDialogVisible: false,
      // 修改用户对话框
      upDatedialogVisible: false,
      // 添加用户对象
      addForm: {
        username: "",
        email: "",
        password: "",
        mobile: ""
      },
      // 修改用户对象
      upDateForm: {},
      // 验证添加表单对象
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名长度在3-10字符之间",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在6-15字符之间",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      upDateFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      // 保存分配角色的用户对象
      userInfo: {},
      // 已选中的角色
      selectedRoleId: "",
      // 所有角色列表数据
      rolesList: []
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 关闭分配角色对话框清空数据
    setRoleDialogClosed() {
      this.selectedRoleId = "";
      this.userInfo = {};
    },
    // 分配用户角色
    async saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error("请选择需要分配的角色");
      }
      const { data: res } = await requestPut(`users/${this.userInfo.id}/role`, {
        rid: this.selectedRoleId
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
      this.getUserList();
      this.assignRolesDialog = false;
    },
    // 分配角色对话框
    async assignRolesDialogClick(userInfo) {
      this.userInfo = userInfo;
      const { data: res } = await requestGet("roles");
      console.log(res);
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      } else {
        this.rolesList = res.data;
      }
      this.assignRolesDialog = true;
    },
    // 根据id删除用户
    removeUserById(id) {
      console.log(id);
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await requestDelete("/users/" + id);

          if (res.meta.status !== 200) {
            this.$message.error("res.meta.msg");
            return;
          }

          this.$message.success(res.meta.msg);
          this.getUserList();
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 修改用户并提交
    upDateUserInfo() {
      this.$refs.upDateFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await requestPut("/users/" + this.upDateForm.id, {
          email: this.upDateForm.email,
          mobile: this.upDateForm.mobile
        });
        console.log(res, "res");
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg);
        } else {
          this.$message.success(res.meta.msg);
          this.getUserList();
          this.upDatedialogVisible = false;
        }
      });
    },
    // 监听修改对话框的关闭事件
    upDatedialogClose() {
      this.$refs.upDateFormRef.resetFields();
    },
    // 修改用户对话框
    async upDateVisible(id) {
      const { data: res } = await requestGet("/users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("查询用户失败");
      }
      this.upDateForm = res.data;
      this.upDatedialogVisible = true;
    },
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await requestPost("/users", this.addForm);
        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败");
        }
        this.$message.success("添加用户成功");
        this.centerDialogVisible = false;
      });
    },
    // 监听用户关闭对话添加用户对话框事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 添加用户弹出对话框
    centerDialog() {
      this.centerDialogVisible = true;
    },
    // 监听pagesize改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 监听 页码值 改变事件
    handleCurrentChange(newSize) {
      this.queryInfo.pagenum = newSize;
      this.getUserList();
    },
    // 监听swithc开关状态
    async userStateChanged(userinfo) {
      // console.log(userinfo);
      let { data: res } = await requestPut(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      // console.log(res);
      if (res.meta.status !== 200) {
        this.$message.error("更新用户状态失败");
        userinfo.mg_state = !userinfo.mg_state;
      } else {
        this.$message.success(res.meta.msg);
      }
    },
    async getUserList() {
      let { data: res } = await requestGet("/users", {
        params: this.queryInfo
      });
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败");
      }
      console.log(res);
      this.userlist = res.data.users;
      this.total = res.data.total;
    }
  }
};
</script>
<style lang="scss" scoped>
.el-card {
  margin-top: 30px;
}
.el-table {
  margin-top: 20px;
}
</style>
